import { View, Image, ViewProps } from "@tarojs/components";
import "./index.less";
import { useState } from "react";
import Taro from "@tarojs/taro";
import MotionDetail from "@/pages/motion/MotionDetail";
import { usePopup } from "@/store/popup";
import { HelpIcon } from "@/components/Icons";
import { getTool } from "@/utils/genNode";

interface Props extends ViewProps {
  img?: string;
  title: string;
  children?: React.ReactNode;
  size?: any;
  showTitle?: boolean;
  detailAction?: string;
  mode?: string;
  onCheck?: () => void;
  showHelp?: boolean;
  canHandle?: boolean;
  isCube?: boolean;
  tool?: any;
}

const ImageCard = ({
  img,
  title,
  className = "",
  children,
  size = Taro.pxTransform(150),
  showTitle = true,
  detailAction,
  mode = "base",
  onCheck,
  showHelp = false,
  canHandle = false,
  isCube = false,
  tool,
  ...others
}: Props) => {
  const url = `${process.env.IMAGE_URL}/motions/min/${img}`;
  const backUrl = `${process.env.IMAGE_URL}/motions/self/${img}`;
  const [currentSrc, setCurrentSrc] = useState(url);

  const { openPopup, closePopup } = usePopup();

  const handleError = () => {
    if (currentSrc !== backUrl) {
      setCurrentSrc(backUrl); // 切换到备用链接
    }
  };

  const handleDetail = (id: string) => {
    const pages = Taro.getCurrentPages();
    if (pages[pages.length - 1].route === "pages/motion/motion") {
      Taro.hideTabBar();
    }

    openPopup({
      showConfirm: false,
      round: false,
      getNode: () => (
        <MotionDetail
          onClose={() => {
            closePopup();
            if (pages[pages.length - 1].route === "pages/motion/motion") {
              Taro.showTabBar();
            }
          }}
          id={id}
          canHandle={canHandle}
        />
      ),
    });
  };

  return (
    <View
      className={`card ${className}`}
      {...others}
      onClick={(e) => {
        e.stopPropagation();
        if (detailAction && mode === "base") {
          handleDetail(detailAction);
        }
        if (mode === "check" && onCheck) {
          onCheck();
        }
      }}
    >
      <View
        className="image-wrapper"
        style={{ height: size, ...(isCube ? { width: size } : {}) }}
      >
        {img ? (
          <Image src={currentSrc} mode="aspectFit" onError={handleError} />
        ) : (
          <View className="empty-image-container">
            {showTitle ? "暂无图片" : title}
          </View>
        )}
        {tool && <View className="image-info">{getTool(tool)}</View>}

        <View className="image-action">
          {showHelp && (
            <HelpIcon
              type="default"
              onClick={(e) => {
                e.stopPropagation();
                detailAction && handleDetail(detailAction);
              }}
            />
          )}
        </View>
      </View>

      {showTitle && <View className="title">{title}</View>}
    </View>
  );
};

export default ImageCard;
